package com.mike.employment.base.config;

import java.util.Date;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;

@Component
@ConfigurationProperties(prefix = "jwt")
@Data
public class JwtConfig {
	private String secret;
	private long expiresSecond;
	private String header;
	private String name;
	 
	 public String createToken (Long userId){
	        Date nowDate = new Date();
	        Date expireDate = new Date(nowDate.getTime() + expiresSecond * 1000);//过期时间
	 
	        return Jwts.builder()
	                .setHeaderParam("typ", "JWT")
	                .setSubject(userId+"")
	                .setIssuedAt(nowDate)
	                .setExpiration(expireDate)
	                .setIssuer(name)
	                .signWith(SignatureAlgorithm.HS512, secret)
	                .compact();
	    }
	 
	 	/**
	     * 获取token中注册信息
	     * @param token
	     * @return
	     */
	    public Claims getTokenClaim (String token) {
	        try {
	            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
	        }catch (Exception e){
               e.printStackTrace();
	            return null;
	        }
	    }
	    
	    public boolean isTokenExpired (Date expirationTime) {
	        return expirationTime.before(new Date());
	    }

	    public Date getExpirationDateFromToken(String token) {
	        return getTokenClaim(token).getExpiration();
	    }
	    
	    public Long getUserIdFromToken(String token) {
	        return Long.parseLong(getTokenClaim(token).getSubject());
	    }

	    
	    public Date getIssuedAtDateFromToken(String token) {
	        return getTokenClaim(token).getIssuedAt();
	    }

}
